// Template with inputs, selects, table with specified columns, pagination
<template>
  <div class="container">
    <div class="flex-container d-flex align-items-center">
      <el-input v-model="name" placeholder="按名称搜索" class="flex-item w-200px" />
      <el-select
        v-model="department"
        placeholder="按部门搜索"
        class="flex-item w-200px ms-5"
        clearable
      >
        <el-option value="研发一部" label="研发一部" />
        <el-option value="研发二部" label="研发二部" />
      </el-select>
      <el-select v-model="sortBy" placeholder="排序依据" class="flex-item w-150px ms-5">
        <el-option value="currentCommitCount" label="本月次数" />
        <el-option value="currentTotalChanges" label="本月代码" />
        <el-option value="commitCount" label="总次数" />
        <el-option value="totalChanges" label="总代码" />
        <el-option value="avgMonthlyCommits" label="月平均提交" />
        <el-option value="avgMonthlyChanges" label="月平均代码" />
        <el-option value="avgWeeklyCommits" label="周平均提交" />
        <el-option value="avgWeeklyChanges" label="周平均代码" />
        <el-option value="avgDayCommits" label="日平均提交" />
        <el-option value="avgDayAdditions" label="日平均新增" />
        <el-option value="avgDayChanges" label="日平均代码" />
        <el-option value="avgActualDayCommits" label="活跃日平均提交" />
        <el-option value="avgActualDayAdditions" label="活跃日平均新增" />
        <el-option value="avgActualDayChanges" label="活跃日平均代码" />
      </el-select>
      <el-select v-model="sortDirection" placeholder="排序方向" class="flex-item w-100px ms-5">
        <el-option value="DESC" label="降序" />
        <el-option value="ASC" label="升序" />
      </el-select>
      <button type="button" class="flex-item btn btn-primary btn-sm ms-2" @click="loadData">
        搜索
      </button>
      <a
        href="#"
        class="flex-item btn btn-icon btn-sm me-5"
        data-bs-toggle="modal"
        data-bs-target="#kt_modal_scrollable_algorithm_desc"
      >
        <i class="fa fa-question text-danger fs-6" title="算法说明"></i>
      </a>
      <AlgorithmDesc />
    </div>
  </div>

  <div class="h-300px mt-3">
    <el-table
      :data="tableData"
      max-height="300px"
      :header-cell-style="{ 'text-align': 'center' }"
      stripe
      @sort-change="handleSortChange"
      @row-click="handleRowClick"
    >
      <!-- 连续序号列 -->
      <el-table-column label="序号" width="40" align="center">
        <template #default="{ $index }">
          <!-- 计算连续序号 -->
          <span>{{ (currentPage - 1) * pageSize + $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" min-width="150">
        <template #default="{ row }">
          <div style="line-height: 16px">
            <span class="fw-bold fs-5">{{ row.name }}</span>
            <KTIcon
              :icon-name="roleSettings[row.role].icon"
              :icon-class="`fs-5 text-${roleSettings[row.role].color} ms-2`"
            />
            <span :class="`badge badge-light-${roleSettings[row.role].color} ms-1`">{{
              roleSettings[row.role].name
            }}</span>
            <br />
            <span class="fs-8 text-gray-500">
              {{ row.department ? row.department.substring(10) : '' }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="本月">
        <el-table-column
          prop="currentCommitCount"
          label="提交"
          align="right"
          sortable="custom"
          min-width="40"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.currentCommitCount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="currentTotalChanges"
          label="代码"
          align="right"
          sortable="custom"
          min-width="80"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.currentTotalChanges }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="总计">
        <el-table-column
          prop="commitCount"
          label="提交"
          align="right"
          sortable="custom"
          min-width="60"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.commitCount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalChanges"
          label="代码"
          align="right"
          sortable="custom"
          min-width="80"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.totalChanges }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="月均">
        <el-table-column
          prop="avgMonthlyCommits"
          label="提交"
          align="right"
          sortable="custom"
          min-width="40"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgMonthlyCommits }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="avgMonthlyChanges"
          label="代码"
          align="right"
          sortable="custom"
          min-width="60"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgMonthlyChanges }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="周均">
        <el-table-column
          prop="avgWeeklyCommits"
          label="提交"
          align="right"
          sortable="custom"
          min-width="40"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgWeeklyCommits }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="avgWeeklyCommits"
          label="代码"
          align="right"
          sortable="custom"
          min-width="60"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgWeeklyChanges }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="工作日均">
        <template #header="{ column }">
          <span>{{ column.label }}</span>
          <i
            class="fa fa-question text-danger fs-6 ms-2"
            title="工作日均：每周5个工作日，排除掉周末。"
          ></i>
        </template>
        <el-table-column
          prop="avgDayCommits"
          label="提交"
          align="right"
          sortable="custom"
          min-width="40"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgDayCommits }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="avgDayAdditions"
          label="增计"
          align="right"
          sortable="custom"
          min-width="50"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgDayAdditions }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="avgDayChanges"
          label="代码"
          align="right"
          sortable="custom"
          min-width="50"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgDayChanges }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="活跃日均">
        <template #header="{ column }">
          <span>{{ column.label }}</span>
          <i
            class="fa fa-question text-danger fs-6 ms-2"
            title="活跃日：排除掉没有提交的日期。"
          ></i>
        </template>
        <el-table-column
          prop="avgActualDayCommits"
          label="提交"
          align="right"
          sortable="custom"
          min-width="40"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgActualDayCommits }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="avgActualDayAdditions"
          label="增计"
          align="right"
          sortable="custom"
          min-width="50"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgActualDayAdditions }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="avgActualDayChanges"
          label="代码"
          align="right"
          sortable="custom"
          min-width="50"
          :sort-orders="['descending', 'ascending']"
        >
          <template #default="{ row }">
            <span style="font-variant-numeric: tabular-nums">{{ row.avgActualDayChanges }}</span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    :page-sizes="[10, 20, 50, 100]"
    style="margin-top: 20px"
    @current-change="loadData"
    @size-change="handleSizeChange"
  />
</template>

<script setup>
// Imports
import { ref, onMounted } from 'vue';
import ApiService from '@/core/services/ApiService';
import AlgorithmDesc from '@/components/biz/AlgorithmDesc.vue';
import { roleSettings } from '@/utils/roleUtils';
import KTIcon from '@/core/helpers/kt-icon/KTIcon.vue';

const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const department = ref('');
const name = ref('');
const sortBy = ref('totalChanges');
const sortDirection = ref('DESC');

// Load data function similar to RepoTableWidget
const loadData = () => {
  const params = {
    page: currentPage.value,
    size: pageSize.value,
    department: department.value || undefined,
    name: name.value || undefined,
    sortBy: sortBy.value,
    sortDirection: sortDirection.value,
  };
  ApiService.query('/api/engineer/stats', { params })
    .then((res) => {
      tableData.value = res.data.records;
      tableData.value.forEach((item) => {
        item.avgMonthlyCommits = item.avgMonthlyCommits ? item.avgMonthlyCommits.toFixed(0) : 0;
        item.avgMonthlyChanges = item.avgMonthlyChanges ? item.avgMonthlyChanges.toFixed(0) : 0;
        item.avgWeeklyCommits = item.avgWeeklyCommits ? item.avgWeeklyCommits.toFixed(0) : 0;
        item.avgWeeklyChanges = item.avgWeeklyChanges ? item.avgWeeklyChanges.toFixed(0) : 0;
        item.avgDayCommits = item.avgDayCommits ? item.avgDayCommits.toFixed(0) : 0;
        item.avgDayChanges = item.avgDayChanges ? item.avgDayChanges.toFixed(0) : 0;
        item.avgActualDayCommits = item.avgActualDayCommits
          ? item.avgActualDayCommits.toFixed(0)
          : 0;
        item.avgActualDayChanges = item.avgActualDayChanges
          ? item.avgActualDayChanges.toFixed(0)
          : 0;
      });
      total.value = res.data.total;

      if (res.data.records.length > 0) {
        emit('row-selected', res.data.records[0]);
      }
    })
    .catch((error) => {
      console.error('Error loading data:', error);
    });
};

// Handle size change, sort change, row click similar to RepoTableWidget

const emit = defineEmits(['row-selected']);

const handleRowClick = (row) => {
  emit('row-selected', row);
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  loadData();
};

const handleSortChange = ({ prop, order }) => {
  sortBy.value = prop;
  sortDirection.value = order === 'ascending' ? 'ASC' : order === 'descending' ? 'DESC' : '';
  loadData();
};

onMounted(loadData);
</script>

<style scoped>
:deep(.el-table__header th) {
  padding: 0px;
}

:deep(.el-table__header .cell) {
  line-height: 12px;
  padding: 5px 0px;
}
</style>
